//
//  GameWindow.m
//  SimpleGameEngine
//
//  Created by Андрей Гукун on 26.12.13.
//  Copyright (c) 2013 Андрей Гукун. All rights reserved.
//

#import "GameWorld.h"

@implementation GameWorld

+(CCScene *) scene
{
	// 'scene' is an autorelease object.
	CCScene *scene = [CCScene node];
	
	// 'layer' is an autorelease object.
	GameWorld *layer = [GameWorld node];
	
	// add layer as a child to scene
	[scene addChild: layer];
	
	// return the scene
	return scene;
}

-(id) init
{
	if( (self=[super init])) {
        bundle = [NSBundle mainBundle];
        g_LuaVM = luaL_newstate();
        luaL_openlibs(g_LuaVM);
        luaopen_io(g_LuaVM);
        luaopen_base(g_LuaVM);
        luaopen_table(g_LuaVM);
        luaopen_string(g_LuaVM);
        luaopen_math(g_LuaVM);
	}
	
	return self;
}

-(void) onEnter
{
    [self DoFile:@"Data/Scripts/MainMenuScreen.lua"];
    [self DoFile:@"Data/Scripts/Init.lua"];
}

-(void) DoFile:(NSString*) relativePath
{
    NSString *path = [[bundle resourcePath] stringByAppendingPathComponent:relativePath];
    NSString *text = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:NULL];
    
    if (luaL_loadbuffer(g_LuaVM, [text UTF8String], [text length], [path UTF8String]) != 0)
        lua_error(g_LuaVM);
    
    lua_call(g_LuaVM, 0, LUA_MULTRET);
    
}

-(void) dealloc
{
    [super dealloc];
    lua_close(g_LuaVM);
}

@end
